package liming.ai;

import liming.ai.client.impl.deepseek.DeepSeekClient;
import liming.ai.core.impl.deepseek.DeepSeekConfig;
import liming.ai.data.deepseek.ChatCompletionRequest;
import liming.ai.data.deepseek.Message;
import liming.ai.tool.ReInput;
import liming.tool.file.FileRW;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

public class Main {
    public static void main(String[] args) throws IOException {
        File file = new File("./config.json");
        DeepSeekClient client = new DeepSeekClient(file);
        DeepSeekConfig config = client.getConfig();

        ReInput input = new ReInput();

        ChatCompletionRequest request = new ChatCompletionRequest();
        if(!config.getTitle().isEmpty())
            request.addMessage(new Message(Message.Role.SYSTEM,config.getTitle()));
        while (true){
            StringBuilder sb = new StringBuilder();
            System.out.println("支持多行输入，输入 \"s\" 发送，" +
                    "输入\"exit\"退出，" +
                    "输入 \"file:\"读取文件或文件夹，" +
                    sb.toString().length());
            System.out.println("请输入问题：");
            input.input(System.console()==null?FileRW.FileEncoding.UTF8: FileRW.FileEncoding.AUTO, str->{
                if(str.startsWith("file:")) {
                    read(sb,new File(str.substring(5)));
                    return true;
                }
                else {
                    sb.append("\n").append(str);
                    return !str.equals("exit") && !str.equals("s");
                }
            });
            if(sb.toString().intern().endsWith("exit"))
                break;
            client.chat(sb.toString(), request);
        }
        System.out.println("结束");
    }
    private static void read(StringBuilder sb,File file) throws IOException {
        if(file==null) {
            return;
        }
        if(file.isDirectory()){
            for(File f : Objects.requireNonNull(file.listFiles()))
                read(sb,f);
        }
        else if(file.isFile()){
            String string = FileRW.readTextFile(file).toString();
            sb.append("\n").append("文件内容：\n").append(string);
            System.out.println("file: "+file+"读取长度："+string.length());
        }
    }
}
